package middlewares

import (
	"github.com/gin-gonic/gin"
	"github.com/shenyisyn/goft-gin/goft"
	"net/http"
	errors2 "sinery.net.goft/src/errors"
)

func ErrorFunc() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if e := recover(); e != nil {
				if e, ok := e.(errors2.MyError); ok {
					code, isExis := c.Get(goft.HTTP_STATUS)
					if isExis {
						c.AbortWithStatusJSON(code.(int), gin.H{"err": e.Err, "errMsg": e.ErrMsg, "data": struct{}{}})
					} else {
						c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"err": e.Err, "errMsg": e.ErrMsg, "data": struct{}{}})
					}
				} else {
					c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"err": e})
				}
			}
		}()
		c.Next()
	}
}
